package com.freewater.library.catalogue.model;

import com.freewater.library.catalogue.model.event.BookCreatedEvent;
import com.freewater.library.common.domain.DomainException;
import com.freewater.library.common.domain.Factory;
import com.freewater.library.common.domain.Nullable;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.Validate;

import java.math.BigDecimal;
import java.time.LocalDate;

@RequiredArgsConstructor
public class BookFactory implements Factory {

    private final BookRepository bookRepository;

    /**
     * 创建书籍
     *
     * @return 书籍
     */
    public Book createBook(String isbn,
                           String title,
                           @Nullable String subtitle,
                           @Nullable String author,
                           @Nullable String publishingHouse,
                           @Nullable LocalDate publicationDate,
                           @Nullable String cover,
                           @Nullable BigDecimal listPrice,
                           @Nullable Integer pageCount,
                           @Nullable String bindingAndLayout,
                           @Nullable String series,
                           @Nullable String description) {
        Validate.notBlank(isbn, "ISBN不能为空");
        Validate.notBlank(title, "标题不能为空");
        boolean exists = this.bookRepository.exists(isbn);
        if (exists) {
            throw new DomainException("已经存在相同ISBN的书籍");
        }
        Book book = new Book(isbn,
                title,
                subtitle,
                author,
                publishingHouse,
                publicationDate,
                cover,
                listPrice,
                pageCount,
                bindingAndLayout,
                series,
                description);
        book.raiseEvent(new BookCreatedEvent(book.getIsbn()));
        return book;
    }
}
